package com.zja.servlet;

import com.zja.model.ArticleViewHistory;
import com.zja.model.JsonResponse;
import com.zja.service.ArticleViewHistoryService;
import com.zja.service.Impl.ArticleViewHistoryServiceImpl;
import com.zja.util.ServletUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author JA
 * @date: 2025/5/7
 * description:分页获取别文章的浏览记录
 */

@WebServlet("/api/viewHistory/list")
public class ListViewHistoryServlet extends HttpServlet {
    private final ArticleViewHistoryService viewHistoryService = new ArticleViewHistoryServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession(false);
        Long authorId = (session != null) ? (Long) session.getAttribute("userId") : null;

        if (authorId == null) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("未登录，无法查看记录"));
            return;
        }

        // 获取分页参数，默认页码为 1，页大小为 10
        int page = 1;
        int pageSize = 10;

        try {
            if (req.getParameter("page") != null) {
                page = Integer.parseInt(req.getParameter("page"));
            }
            if (req.getParameter("pageSize") != null) {
                pageSize = Integer.parseInt(req.getParameter("pageSize"));
            }
        } catch (NumberFormatException e) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("分页参数不合法"));
            return;
        }

        // 获取记录数据和总数
        List<ArticleViewHistory> records = viewHistoryService.getViewRecordsOfMyArticles(authorId, page, pageSize);
        int total = viewHistoryService.countViewRecordsOfMyArticles(authorId);

        // 封装结果
        Map<String, Object> data = new HashMap<>();
        data.put("records", records);
        data.put("total", total);
        data.put("page", page);
        data.put("pageSize", pageSize);

        ServletUtil.writeJsonResponse(resp, JsonResponse.success(data));
    }
}
